#include "Toast.h"
#include "ToastGenerator.h"
#include <QApplication>

namespace TWCore
{
	ToastGenerator::ToastGenerator():QObject(0),m_toastParent(0){}

	ToastGenerator::~ToastGenerator()
	{
		qDeleteAll(m_toasts);

		QMapIterator<int,QList<PendingToast*>* > i(m_pendingToasts);
		while(i.hasNext())
		{
			QList<PendingToast*>* list = i.next().value();
			qDeleteAll(*list);
			delete list;
		}
	}

	void ToastGenerator::makeToast(QString msg,int x,int y,int duration,int index)
	{
		if(!m_toastIsUsingMap.contains(index))
		{
			Toast* t = new Toast(m_toastParent,index);
			m_toasts.insert(index,t);
			m_toastIsUsingMap.insert(index,false);
			QList<PendingToast*>* list = new QList<PendingToast*>();
			m_pendingToasts.insert(index,list);
			connect(t,SIGNAL(fadeOut(int)),this,SLOT(toastNext(int)));
		}

		if(m_toastIsUsingMap.value(index))
		{
			QList<PendingToast*>* list = m_pendingToasts[index];
			PendingToast* pt = new PendingToast();
			pt->msg = msg;
			pt->x = x;
			pt->y = y;
			pt->duration = duration;
			list->append(pt);
		}else
		{
			Toast* w = m_toasts.value(index);
			w->show(msg,x,y,duration);
			m_toastIsUsingMap.insert(index,true);
		}
	}

	void ToastGenerator::toastNext(int index)
	{
		QList<PendingToast*>* list = m_pendingToasts.value(index);
		if(list->isEmpty())
			m_toastIsUsingMap.insert(index,false);
		else
		{
			PendingToast* pending = list->takeFirst();
			Toast* w = m_toasts.value(index);
			w->show(pending->msg,pending->x,pending->y,pending->duration);
			delete pending;
		}
	}
}
